﻿// Contains information about the browser viewport to allow testing a pop up control if it fits the visible area
define([
    'Xjs/core/dom'
],
function (dom) {
    'use strict';

    console.log('Entering viewport module');

    return {

        // Adjust the position of the element so it will remain completely visible on the viewport
        // If the parent p is provided, then move it around the parent so it will not be shadowed
        adjust: function (el, p) {

            if (!el || 1 !== el.nodeType) {
                return;
            }

            var r = el.getBoundingClientRect(),
                root = document.documentElement,
                pos;

            if (r.bottom > root.clientHeight) { // Need to move it up
                if (p) { // Place it above the parent to not to shadow it
                    pos = dom.height(p);
                }
                else { // Move it up so it will completely visible
                    pos = 0;
                }

                dom.setBottom(el, pos);
            }

            if (r.top < 0) { // Need to move it down
                if (p) { // Place it below the parent to not to shadow it
                    pos = dom.height(p);
                }
                else { // Move it down so it will completely visible
                    pos = 0;
                }

                dom.setTop(el, pos);
            }

            if (r.right > root.clientWidth) { // Need to move it to the left
                if (p) { // Place it left to the parent to not to shadow it
                    pos = dom.width(p);
                }
                else { // Move it left so it will completely visible
                    pos = 0;
                }

                dom.setRight(el, pos);
            }

            if (r.left < 0) { // Need to move it to the right
                if (p) { // Place it below the parent to not to shadow it
                    pos = dom.right(p);
                }
                else { // Move it down so it will completely visible
                    pos = 0;
                }

                dom.setLeft(el, pos);
            }
        }
    };
});